package sub

import (
	"fmt"
	"quipus/cmd/qpc/sub"
	"quipus/internal/utils"
	v1pb "quipus/proto/gen/api/v1"
	cpb "quipus/proto/gen/common"

	"strings"

	"github.com/spf13/cobra"
)

var (
	matter     string
	granaryIds []int32
	ragMode    string
	Artifact   string
)

func init() {
	createCmd.PersistentFlags().StringVarP(&matter, "matter", "m", "", "the matter of subject")
	createCmd.PersistentFlags().StringVarP(&Artifact, "Artifact", "a", "", "the Artifact may be a flow urn or a assistant urn")

	createCmd.PersistentFlags().Int32SliceVarP(&granaryIds, "granary", "g", []int32{}, "the granary ids of granary")
	createCmd.PersistentFlags().StringVarP(&ragMode, "rag-mode", "r", "", "the rag mode of subject: naive, kg")

	subjectCmd.AddCommand(createCmd)
}

var createCmd = &cobra.Command{
	Use:   "create",
	Short: "Run the cmd to create subject",
	RunE: func(cmd *cobra.Command, args []string) error {
		qconn, e := sub.NewGrpcConnect(sub.QpConfig.QPAddress)
		if e != nil {
			return e
		}

		qclient := v1pb.NewSubjectServiceClient(qconn)
		ctxWithToken := sub.NewCtxWithToken(sub.QpConfig.Token)
		var granaryies []string
		for _, granaryId := range granaryIds {
			granaryies = append(granaryies, utils.BuildUrn(utils.GranaryUrnPrefix, granaryId))
		}

		in := &v1pb.CreateSubjectRequest{Matter: matter, Granaries: granaryies}

		ragMode := strings.ToUpper(ragMode)
		switch ragMode {
		case "NAIVE":
			in.RagMode = cpb.RagMode_NAIVE
		case "KG":
			in.RagMode = cpb.RagMode_KG
		default:
			in.RagMode = cpb.RagMode_NAIVE
		}

		rsp, err := qclient.CreateSubject(ctxWithToken, in)
		if err != nil {
			return err
		}
		fmt.Print(rsp)
		return nil
	},
}
